package com.government.web.controller.item;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.government.common.annotation.Anonymous;
import com.government.common.annotation.RepeatSubmit;
import com.government.common.config.GovernmentConfig;
import com.government.common.core.domain.entity.SysUser;
import com.government.common.utils.file.FileUploadUtils;
import com.government.framework.config.ServerConfig;
import com.government.item.bo.ItemDataListBO;
import com.government.item.domain.ExcelDetail;
import com.government.item.vo.ItemData;
import com.government.item.vo.ItemStatisticsData;
import com.government.system.domain.UploadFiles;
import com.government.system.mapper.UploadFilesMapper;
import com.government.util.Documents4jUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.government.common.annotation.Log;
import com.government.common.core.controller.BaseController;
import com.government.common.core.domain.AjaxResult;
import com.government.common.enums.BusinessType;
import com.government.item.domain.ExcelList;
import com.government.item.service.IExcelListService;
import com.government.common.utils.poi.ExcelUtil;
import com.government.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import static com.government.common.utils.SecurityUtils.getLoginUser;

/**
 * excel记录Controller
 *
 * @author system
 * @date 2023-09-19
 */
@RestController
@RequestMapping("/item/item")
public class ExcelListController extends BaseController {
    @Autowired
    private IExcelListService excelListService;

    @Autowired
    private ServerConfig serverConfig;

    private static final String FILE_DELIMETER = ",";

    @Autowired
    private UploadFilesMapper uploadFilesMapper;

    /**
     * 查询excel记录列表
     */
    @PreAuthorize("@ss.hasPermi('item:item:list')")
    @GetMapping("/list")
    public TableDataInfo list(ExcelList excelList) {
        startPage();
        List<ExcelList> list = excelListService.selectExcelListList(excelList);
        return getDataTable(list);
    }

    /**
     * 导出excel记录列表
     */
    @Log(title = "excel记录", businessType = BusinessType.EXPORT)
    @PostMapping("/download")
    public void download(HttpServletResponse response, Long id) {
        List<ExcelDetail> list = excelListService.getExcelDetail(id);
        ExcelUtil<ExcelDetail> util = new ExcelUtil<ExcelDetail>(ExcelDetail.class);
        util.exportExcel(response, list, "立项数据");
    }

    /**
     * 获取excel记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('item:item:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(excelListService.selectExcelListById(id));
    }

    /**
     * 新增excel记录
     */
    @RepeatSubmit
    @PreAuthorize("@ss.hasPermi('item:item:add')")
    @Log(title = "excel记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ExcelList excelList) {
        return toAjax(excelListService.insertExcelList(excelList));
    }

    /**
     * 修改excel记录
     */
    @PreAuthorize("@ss.hasPermi('item:item:edit')")
    @Log(title = "excel记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ExcelList excelList) {
        return toAjax(excelListService.updateExcelList(excelList));
    }

    /**
     * 删除excel记录
     */
    @PreAuthorize("@ss.hasPermi('item:item:remove')")
    @Log(title = "excel记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        return toAjax(excelListService.deleteExcelListById(id));
    }

    /**
     *
     */
    @GetMapping("/getItemDataList")
    public TableDataInfo getItemDataList(Long policyId) {
        startPage();
        List<ItemData> list = excelListService.getItemDataList(policyId);
        return getDataTable(list);
    }

    /**
     * 导入立项数据
     *
     * @param file
     * @param policyId
     * @return
     * @throws Exception
     */
    @RepeatSubmit
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, String policyId) throws Exception {

        SysUser user = getLoginUser().getUser();

        // 上传文件路径
        String filePath = GovernmentConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.upload(filePath, file);
        String url = serverConfig.getUrl() + fileName;

        UploadFiles uploadFiles = new UploadFiles();
        uploadFiles.setFileUrl(fileName);
        uploadFiles.setFromName(file.getOriginalFilename());
        uploadFiles.setCreateTime(new Date());
        uploadFiles.setCreateBy(String.valueOf(user.getUserId()));
        uploadFilesMapper.insert(uploadFiles);

        ExcelUtil<ExcelDetail> util = new ExcelUtil<ExcelDetail>(ExcelDetail.class);
        List<ExcelDetail> excelDetailList = util.importExcel(file.getInputStream());
        excelListService.importData(url, excelDetailList, policyId, file.getOriginalFilename());
        return success();
    }

    /**
     * 获取金额维度立项数据统计
     */
    @GetMapping("/getItemStatisticsByAmount")
    public AjaxResult getItemStatisticsByAmount(ItemDataListBO bo) {

        List<ItemStatisticsData> list = excelListService.getItemStatisticsByAmount(bo);
        return AjaxResult.success(list);
    }

    /**
     * 获取地区维度立项数据统计
     */
    @GetMapping("/getItemStatisticsByArea")
    public AjaxResult getItemStatisticsByArea(ItemDataListBO bo) {

        List<ItemStatisticsData> list = excelListService.getItemStatisticsByArea(bo);
        return AjaxResult.success(list);
    }

    /**
     * 获取性质维度立项数据统计
     */
    @GetMapping("/getItemStatisticsByNature")
    public AjaxResult getItemStatisticsByNature(ItemDataListBO bo) {

        List<ItemStatisticsData> list = excelListService.getItemStatisticsByNature(bo);
        return AjaxResult.success(list);
    }

    /**
     * 获取行业维度立项数据统计
     */
    @GetMapping("/getItemStatisticsByIndustry")
    public AjaxResult getItemStatisticsByIndustry(ItemDataListBO bo) {

        List<ItemStatisticsData> list = excelListService.getItemStatisticsByIndustry(bo);
        return AjaxResult.success(list);
    }

    /**
     * 获取单位、金额维度立项数据统计
     */
    @GetMapping("/getCompanyItemStatisticsByAmount")
    public AjaxResult getCompanyItemStatisticsByAmount(ItemDataListBO bo) {

        List<ItemStatisticsData> list = excelListService.getCompanyItemStatisticsByAmount(bo);
        return AjaxResult.success(list);
    }

    /**
     * 获取单位、政策所属主管部门维度立项数据统计
     */
    @GetMapping("/getCompanyItemStatisticsByOrg")
    public AjaxResult getCompanyItemStatisticsByOrg(ItemDataListBO bo) {

        List<ItemStatisticsData> list = excelListService.getCompanyItemStatisticsByOrg(bo);
        return AjaxResult.success(list);
    }

    /**
     * 获取单位、政策层级维度立项数据统计
     */
    @GetMapping("/getCompanyItemStatisticsByLevel")
    public AjaxResult getCompanyItemStatisticsByLevel(ItemDataListBO bo) {

        List<ItemStatisticsData> list = excelListService.getCompanyItemStatisticsByLevel(bo);
        return AjaxResult.success(list);
    }

    /**
     * 获取单位、政策批次维度立项数据统计
     */
    @GetMapping("/getCompanyItemStatisticsByYear")
    public AjaxResult getCompanyItemStatisticsByYear(ItemDataListBO bo) {

        List<ItemStatisticsData> list = excelListService.getCompanyItemStatisticsByYear(bo);
        return AjaxResult.success(list);
    }

    /**
     * 获取单位、政策批次维度立项数据统计
     */
    @GetMapping("/getCompanyItemStatistics")
    public AjaxResult getCompanyItemStatistics(ItemDataListBO bo) {

        String result = excelListService.getCompanyItemStatistics(bo);
        return AjaxResult.success(result);
    }

    /**
     * 立项数据修复程序
     */
    @PostMapping("/failDataHandler")
    @Anonymous
    public AjaxResult failDataHandler() {

        excelListService.failDataHandler();
        return AjaxResult.success();
    }
}
